package top.zsyle.sycc.mq.listener;

import bo.CourseOrderPayBo;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.json.Json;
import top.zsyle.sycc.domain.CourseOrder;
import top.zsyle.sycc.exception.GlobalException;
import top.zsyle.sycc.exception.GlobalExceptionEnum;
import top.zsyle.sycc.service.ICourseOrderService;

import java.nio.charset.StandardCharsets;

@RocketMQTransactionListener(txProducerGroup = "tx-course-order-pay-producer-group")
@Component
@Slf4j
public class TxCourseOrderPayListener implements RocketMQLocalTransactionListener {

    @Autowired
    private ICourseOrderService courseOrderService;

    /**
     * 执行本地事务
     * @param message
     * @param arg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        //校验参数
        try {
            if(arg == null){
                log.error("执行订单本地事务失败，失败原因：没有执行本地事务相关参数！");
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            CourseOrder courseOrder = JSON.parseObject(JSON.toJSONString(arg), CourseOrder.class);
            //执行本地事务
            courseOrderService.insertCourseOrderAndCourseOrderItem(courseOrder);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    /**
     * 事务回查方法
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        byte[] body = (byte[]) message.getPayload();
        if(body.length == 0){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        //查询是否有该订单号的课程订单
        CourseOrderPayBo courseOrderPayBo = JSON.parseObject(new String(body, StandardCharsets.UTF_8), CourseOrderPayBo.class);
        CourseOrder courseOrder = courseOrderService.selectByOrderNo(courseOrderPayBo.getOrderNo());
        if (courseOrder == null){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }
}
